package com.zx._09_架构.扩展性.cpt1_event.handler;

import com.zx._09_架构.扩展性.cpt1_event.event.AddEvent;
import com.zx._09_架构.扩展性.cpt1_event.event.Event;
import com.zx._09_架构.扩展性.cpt1_event.event.UpStringEvent;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 事件处理器
 *
 * @param <T>
 */
public abstract class EventHandler<T extends Event> {


    private static Map<String, EventHandler> HANDLER_MAP = new HashMap<>();
    static {
        HANDLER_MAP.put(AddEvent.class.getName(), new AddEventHandler());
        HANDLER_MAP.put(UpStringEvent.class.getName(), new UpStringEventHandler());
    }

    /**
     * 发布事件
     * @param event
     * @return
     */
    public static boolean publicEvent(Event event) {
        EventHandler handler = HANDLER_MAP.get(event.getClass().getName());
        return handler.on(event);
    }
    /**
     * 处理事件
     *
     * @param event
     * @return
     */
    public abstract boolean on(T event);

    /**
     * 获得参数的类型
     *
     * @return
     */
    public Class<T> paramType() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<T>) params[0];
    }

}
